package com.lxj.xianyu;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/xianyu")
public class XianyuController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SpiderService spiderService;

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @ResponseBody
    @GetMapping("/list")
    public List<Item> get(HttpServletRequest request) {
        String keyword = request.getParameter("keyword");

        spiderService.execute();

        Long size = 100L;//stringRedisTemplate.opsForList().size(keyword);
        List<String> range = stringRedisTemplate.opsForList().range(keyword, 0, size - 1L);
        if (!CollectionUtils.isEmpty(range)) {
            return JSON.parseArray(range.toString(), Item.class);
        }
        return null;
    }

    @ResponseBody
    @GetMapping("/keywords")
    public Set<String> keywords() {
        Set<String> keywords = stringRedisTemplate.opsForSet().members("keywords");
        return keywords;
    }

    @ResponseBody
    @PostMapping("/add")
    public Long add(HttpServletRequest request) {
        String keyword = request.getParameter("keyword");
        Long keywords = stringRedisTemplate.opsForSet().add("keywords", keyword);
        return keywords;
    }

    @ResponseBody
    @PostMapping("/remove")
    public Long remove(@RequestParam("keyword") String keyword) {
        if (StringUtils.isNotBlank(keyword)) {
            String[] strings = keyword.split(",");
            for (String s : strings) {
                stringRedisTemplate.opsForSet().remove("keywords", s);
            }
            return 1L;
        }
        return 0L;
    }
}
